<?php
/**
 *
 * Created by PhpStorm.
 * User: Earl <guo@seosite.cn>
 * Date: 2017/9/25
 * Time: 下午5:33
 * deadline:2018年01月23日13:38:01
 */
namespace App\Controller;

header('content-type:text/html;charset=utf-8');
class UserController extends BaseController {

    /**
     * @desc 获取验证码
     * @author Earl <guo@seosite.cn> .
     * @updateTime
     */
    public function verify($uuid)
    {
        $sendVerifyName= $uuid;

        $sendVerifyName = md5($sendVerifyName . '12345');
        $config =    array(
            'fontSize'    =>    40,    // 验证码字体大小
            'length'      =>    4,     // 验证码位数
            'useNoise'    =>    true, // 关闭验证码杂点
            'useZh'       =>    false, // 开启中文验证码
            'codeSet'       =>    '0123456789', // 开启中文验证码
        );
        $Verify =     new \Think\Verify($config);
        if ($Verify->useZh){
            $Verify->fontttf = '7.ttf';
        }else{
            $Verify->useImgBg = false;
            $Verify->length = 4;
        }
        $Verify->entry();

        $key = substr(md5($Verify->seKey), 5, 8);
        $str = substr(md5($Verify->seKey), 8, 10);
        $key = md5($key . $str);
        S($sendVerifyName, session($key), 180);
    }

	/**
	 * @desc 用户登陆
	 * @param $phone     用户账户:用户名，ID号，手机号
	 * @param $password  用户密码
     * @param $remember 记住密码 1 是，0否
	 * @return string
	 */
	public function login($param)
    {
        $check = CheckFactoryController::isParamSet();
        $check->before($param);

        $check = CheckFactoryController::isChildParamSet();
        $check->before('username,password,verify');

        unset($check);

		$password = md5($param['password']);
		$username = $param['username'];

        $verifyName = I('post.uuid');
        $verify = $param['verify'];

        $sendVerifyName = md5($verifyName . '12345');
        $Verify = new \Think\Verify();
        $key = substr(md5($Verify->seKey), 5, 8);
        $str = substr(md5($verify), 8, 10);
        $key = md5($key . $str);


        if (!S($sendVerifyName) || S($sendVerifyName)['verify_code']!=$key){
            return showErrorMsg(L("_OPERATION_FAIL_").L('_SMSCODE_ERROR_'),100002);
        }

		//过期时间，记住设置为0不过期，不记住 设置token失效时间为3天
        $expire_time = empty($param['remember'])?259200:0;

		$model = M('user');
		$map['u_no'] = $username;
		$map['phone']           = $username;
		$map['email']           = $username;
		$map['account']        = $username;
		$map['_logic'] ='or';
        $condition['_complex'] = $map;
		$condition['password'] = $password;

		$userinfo = $model->field('id,username,headsmall,logins,status')->where($condition)->find();

		if($userinfo){
			if($userinfo['status']!=0){
				$user_save_data['logins'] = $userinfo['logins'] + 1;
                $user_save_data['last_ip'] = client_ip();
                $user_save_data['last_time'] = time();
                $user_save_data['id'] = $userinfo['id'];
				$reslogin = $model->save($user_save_data);
				if($reslogin){
				    $token_info = [
				        'id'    =>  $userinfo['id'],
                        'username'  =>  $userinfo['username'],
                    ];
					$token = _set_token($token_info,$expire_time);
					$userinfo['token']    = $token;

//					$ImObj = new ImController();
//                    $userinfo['ImToken'] = $ImObj->getImToken($userinfo['id']);

					if($token)  return showErrorMsg($msg = L('_OPERATION_SUCCESS_'),$code = 0,$return_type = 2,$return_data = $userinfo);
					if(!$token) return showErrorMsg($msg = L('_TOKEN_BUILD_ERROR_'),$code = 100004);
				}
				if(!$reslogin) return showErrorMsg($msg = L('_TOKEN_BUILD_ERROR_'),$code = 100002);
			}
			if($userinfo['status']!=1) return showErrorMsg($msg = L('_ACCOUNT_DISABLED_'),$code = 100002);
		}
		if(!$userinfo) return showErrorMsg($msg = L('_LOGIN_ERROR_'),$code = 100002);
	}

    /**
     * @desc 修改密码
     * @param $param
     * @return array
     */
    public function updatePwd($param)
    {
        $check = CheckFactoryController::isLogin();
        $check->before($param);

        $check = CheckFactoryController::isParamSet();
        $check->before($param);

        $check = CheckFactoryController::isChildParamSet();
        $check->before('o_pwd,n_pwd,r_pwd');

        unset($check);

        $old_pwd = $param['o_pwd'];
        $new_pwd = $param['n_pwd'];
        $re_new_pwd = $param['r_pwd'];

        if ($new_pwd != $re_new_pwd) return showErrorMsg(L('_PWD_NOT_UNITE_'),100002);

        $y_pwd = M('User')->where(['id'=>$this->userInfo->id])->getField('password');
        if (md5($old_pwd)!=$y_pwd) return showErrorMsg(L('_PWD_FIRST_ERROR_'),100002);


        $operation = M('User')->where(['id'=>$this->userInfo->id])->setField('password',md5($new_pwd));

        if ($operation) {
            $info = M('User')->field('id,username,headsmall,logins,status')->find($this->userInfo->id);
            $token = _set_token($info,0);
            $userinfo = decode_token($token);
            $userinfo['token']    = $token;
            return showErrorMsg(L("_OPERATION_SUCCESS_"),0,2,$userinfo);
        }else{
            if ($old_pwd == $new_pwd)return showErrorMsg('新旧密码不能相同',100002);
            return showErrorMsg(L("_OPERATION_FAIL_"));
        }

    }

	/**
	 * @desc 退出登陆 
	 * @return string
	 */
	public function logout(){
        if (empty($this->userInfo)) return showErrorMsg(L('_TOKEN_USELESS_'),100004);
		$map['uid'] = $this->userInfo->id;
        $map['platform'] = 'app';
		$Re = M('Token')->where($map)->delete();
		if($Re)  return showErrorMsg($msg = L('_OPERATION_SUCCESS_'),$code = 0,$return_type = 2,$return_data = $map);
		if(!$Re) return showErrorMsg($msg = L('_OPERATION_FAIL_'),$code = 100002);
	}

}